package com.ilovepostcard;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import com.ilovepostcard.controller.BaseAsyncTask;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.NetWorkUtil;
import com.ilovepostcard.utils.StringUtils;
import com.ilovepostcard.utils.ThirdPartyLoginUtil;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

public class HomeActivity extends BaseActivity {

    public static final int REQUEST_CODE_REGISTER = 103;
    public static final int REQUEST_CODE_LOGIN = 104;
    public static final int RESULT_CODE_SINA = 1;
    public static final int RESULT_CODE_TENCENT = 2;
    public static final int RESULT_CODE_REGISTER_SUCCESS = 3;
    public static final int RESULT_CODE_GOTO_REGISTER = 4;
    
    private BroadcastReceiver loginSuccessReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        IntentFilter filter = new IntentFilter(Actions.ACTION_LOGIN_SUCCESS);
        registerReceiver(loginSuccessReceiver, filter);
        
        if (!NetWorkUtil.isNetworkAvailable(this)) {
            Toast.makeText(this, "目前没有网络哦~", Toast.LENGTH_LONG).show();
        }
        
        
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_LOGIN || requestCode == REQUEST_CODE_REGISTER) {
            if (requestCode == REQUEST_CODE_LOGIN && resultCode == RESULT_CODE_GOTO_REGISTER) {
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivityForResult(intent, HomeActivity.REQUEST_CODE_REGISTER);
            } else if (requestCode == REQUEST_CODE_REGISTER && resultCode == RESULT_CODE_REGISTER_SUCCESS) {
                final String email = data.getStringExtra("email");
                final String pwd = data.getStringExtra("pwd");
                new ServerAsyncTask(this) {
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        User user = new User();
                        /* the result is uid */
                        user.UserID = result.getResult();
                        user.Username = email;
                        UserController.saveLoginUser(context, user);
                        /* now only used to notify the LoginActivity to finish itself. */
                        context.sendBroadcast(new Intent(Actions.ACTION_LOGIN_SUCCESS));
                        ((Activity)context).finish();
                        Intent intent = new Intent(context, MainActivity.class);
                        context.startActivity(intent);
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().login(email, pwd);
                    }
                }.execute();
            } else if (resultCode == RESULT_CODE_SINA) {
                ThirdPartyLoginUtil.sinaLogin(HomeActivity.this);
            } else if (resultCode == RESULT_CODE_TENCENT) {
                ThirdPartyLoginUtil.tencentLogin(HomeActivity.this);
            }
        } else if (requestCode == ThirdPartyLoginUtil.TENCENT_LOGIN_REQUEST_CODE) {
            if (resultCode == OAuthV2AuthorizeWebView.RESULT_CODE) {
                // 取得返回的OAuthV2类实例oAuth
                final OAuthV2 oAuth = (OAuthV2) data.getExtras()
                        .getSerializable("oauth");
                new BaseAsyncTask() {

                    ProgressDialog pd;
                    String nick;
                    String name;
                    String headUrl;

                    @Override
                    protected void _onPreExecute() {
                        pd = new ProgressDialog(HomeActivity.this);
                        pd.setMessage("获取腾讯微博用户信息...");
                        pd.show();
                    }

                    @Override
                    protected void _doInBackground() {
                        try {
                            // UserAPI userAPI=new
                            // UserAPI(OAuthConstants.OAUTH_VERSION_1);
                            // 若调用2.0 API 以上一行请换为
                            UserAPI userAPI = new UserAPI(
                                    OAuthConstants.OAUTH_VERSION_2_A);

                            String response = userAPI.info(oAuth, "json");// 获取用户信息
                            userAPI.shutdownConnection();
                            JSONObject jsonObject = new JSONObject(response);
                            name = jsonObject.getJSONObject("data").getString("name");
                            nick = jsonObject.getJSONObject("data")
                                    .getString("nick");
                            headUrl = jsonObject.getJSONObject("data").getString("head");
                            if (StringUtils.isNotEmpty(headUrl)) {
                                headUrl += "/100"; /* must add /100 means 100*100 size */
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    protected void _onPostExecute() {
                        pd.dismiss();
                        if (nick != null && name != null) {
                            User user = new User();
                            /* the result is uid */
                            user.Username = name;
                            user.Nickname = nick;
                            
                            new ServerAsyncTask(HomeActivity.this) {
                                
                                @Override
                                protected void onSuccess(PostcardResult result) {
                                    User user = new User();
                                    /* the result is uid */
                                    user.UserID = result.getResult();
                                    user.Username = name;
                                    UserController.saveLoginUser(context, user);
                                    /* now only used to notify the LoginActivity to finish itself. */
                                    context.sendBroadcast(new Intent(Actions.ACTION_LOGIN_SUCCESS));
                                    ((Activity)context).finish();
                                    Intent intent = new Intent(context, MainActivity.class);
                                    context.startActivity(intent);
//                                    Toast.makeText(HomeActivity.this, "你好 " + nick, Toast.LENGTH_SHORT).show();
                                    
                                    ThirdPartyLoginUtil.uploadThirdPartyHead(HomeActivity.this, headUrl, user.UserID);
                                }
                                
                                @Override
                                protected PostcardResult doRequest() {
                                    return ServerFactory.getServer().userLoginFromOpen(name, nick, IServer.OPEN_TYPE_QQ);
                                }
                            }.execute();
                            
//                            UserController.saveLoginUser(HomeActivity.this, user);
//                            /* now only used to notify the LoginActivity to finish itself. */
//                            HomeActivity.this.sendBroadcast(new Intent(Actions.ACTION_LOGIN_SUCCESS));
//                            HomeActivity.this.finish();
//                            Intent intent = new Intent(HomeActivity.this, MainActivity.class);
//                            HomeActivity.this.startActivity(intent);
//                            Toast.makeText(HomeActivity.this, "Hello " + nick, Toast.LENGTH_SHORT).show();
                        } else {
//                            Toast.makeText(HomeActivity.this, "获取微薄用户信息失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                }.execute();
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(loginSuccessReceiver);
        super.onDestroy();
    }

}
